/**
 *    TimedProfiles - let Android perform tasks based on conditions
 *    Copyright (C) 2011  Daniel Weinhold
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * */
package de.drak.Profiles.plugins;

import java.util.Calendar;

import de.drak.Profiles.OnlineHelp;
import de.drak.Profiles.R;
import de.drak.Profiles.TimedProfiles;

import android.app.Activity;
import android.widget.TextView;
import android.widget.TimePicker;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Surface;
import android.view.WindowManager;
import android.widget.LinearLayout;

/*
 * PendingIntent  operation = getActivity(Context, int, Intent, int), getBroadcast(Context, int, Intent, int), getService(Context, int, Intent, int);
 * AlarmManager timer = Context.getSystemService(Context.ALARM_SERVICE);
 * timer.set(int type, long triggerAtTime, operation)
 * timer.setRepeating(int type, long triggerAtTime, long interval, operation)
 */

/**Used to Edit a Time Condition. Pick a slice of Time*/
public class TimePickerPlug extends Activity {

	private static final int MENU_SAVE = 1;
	private static final int MENU_DONT_SAVE = 2;
	
	static final String STORE_START = "time.s";
	static final String STORE_END = "time.e";

	/**Indicates if Activity should return RESULT_CANCELED*/
	private boolean isCancelled;
	private TimePicker start;
	private TimePicker ende;

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void onCreate(final Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		LinearLayout mmain = new LinearLayout(this);
		LinearLayout main = new LinearLayout(this);
		mmain.addView(main);
		setContentView(mmain);
		main.setBackgroundResource(android.R.drawable.alert_dark_frame);

        //load title
		TimedProfiles.createTitle(this, getString(R.string.plugin_timepicker));
		
		
		start = new TimePicker(this);
		ende = new TimePicker(this);
		
		start.setIs24HourView(true);
		ende.setIs24HourView(true);
		
		
		if(Surface.ROTATION_90 == ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay().getOrientation())
		{
			main.setOrientation(LinearLayout.HORIZONTAL);
		}else{
			main.setOrientation(LinearLayout.VERTICAL);
		}
		
		mmain.setGravity(Gravity.CENTER_HORIZONTAL);
		TextView t = new TextView(this);
		t.setText(R.string.plugin_timepicker_start);
		t.setTextColor(Color.argb(255, 255, 255, 255));
		main.addView(t);
		main.addView(start);
		t = new TextView(this);
		t.setText(R.string.plugin_timepicker_end);
		t.setTextColor(Color.argb(255, 255, 255, 255));
		main.addView(t);
		main.addView(ende);


		/*
		 * if savedInstanceState == null, then we are entering the Activity directly and we need to check whether the
		 * Intent has forwarded a Bundle extra (e.g. whether we editing an old condition or creating a new one)
		 */
		if (savedInstanceState == null)
		{
			final Bundle forwardedBundle = getIntent().getBundleExtra(QueryReceiver.INTENT_BUNDLE);

			/*
			 * the forwardedBundle would be null if this was a new condition
			 */
			if (forwardedBundle == null)
			{
		        final Calendar c = Calendar.getInstance();
		        int h = c.get(Calendar.HOUR_OF_DAY);
		        int m = c.get(Calendar.MINUTE);
				start.setCurrentHour(h);
				start.setCurrentMinute(m);
				c.add(Calendar.HOUR_OF_DAY,1);
				h = c.get(Calendar.HOUR_OF_DAY);
				ende.setCurrentHour(h);
				ende.setCurrentMinute(m);
		    }else{
		    	Calendar s = Calendar.getInstance(), e = Calendar.getInstance();
		    	s.setTimeInMillis(forwardedBundle.getLong(STORE_START));
		    	e.setTimeInMillis(forwardedBundle.getLong(STORE_END));
				start.setCurrentHour(s.get(Calendar.HOUR_OF_DAY));
				start.setCurrentMinute(s.get(Calendar.MINUTE));
				ende.setCurrentHour(e.get(Calendar.HOUR_OF_DAY));
				ende.setCurrentMinute(e.get(Calendar.MINUTE));				
			}
		}
		/*
		 * if savedInstanceState != null, there is no need to restore any Activity state directly (e.g. onSaveInstanceState()).
		 * This is handled by the Spinner automatically
		 */
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void finish()
	{
		if (isCancelled)
			setResult(RESULT_CANCELED);
		else
		{

			/*
			 * This is the return Intent, into which we'll put all the required extras
			 */
			final Intent returnIntent = new Intent();

			/*
			 * This extra is the data to ourselves: either for the Activity or the BroadcastReceiver. Note that anything placed in
			 * this Bundle must be available to Locale's class loader. So storing String, int, and other basic objects will work
			 * just fine. You cannot store an object that only exists in your app, as Locale will be unable to serialize it.
			 */
			final Bundle storeAndForwardExtras = new Bundle();
			
			returnIntent.putExtra(TimedProfiles.INTENT_INFO_STR, String.format("%s %d:%d %s %d:%d", 
					getString(R.string.plugin_timepicker_start),
					start.getCurrentHour(), start.getCurrentMinute(),
					getString(R.string.plugin_timepicker_end),
					ende.getCurrentHour(), ende.getCurrentMinute()));
			
			Calendar s = Calendar.getInstance(), e = Calendar.getInstance();
	        s.set(Calendar.HOUR_OF_DAY, start.getCurrentHour());
	        s.set(Calendar.MINUTE, start.getCurrentMinute());
	        e.set(Calendar.HOUR_OF_DAY, ende.getCurrentHour());
	        e.set(Calendar.MINUTE, ende.getCurrentMinute());
	        
			storeAndForwardExtras.putLong(STORE_START, s.getTimeInMillis());
			storeAndForwardExtras.putLong(STORE_END, e.getTimeInMillis());
			
			storeAndForwardExtras.putInt(QueryReceiver.TYPE_FIELD, QueryReceiver.IS_TIME);
			returnIntent.putExtra(QueryReceiver.INTENT_BUNDLE, storeAndForwardExtras);

			setResult(RESULT_OK, returnIntent);
		}

		super.finish();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean onCreateOptionsMenu(final Menu menu)
	{
		super.onCreateOptionsMenu(menu);

		final Intent helpIntent = new Intent(this, OnlineHelp.class);
		helpIntent.putExtra("com.twofortyfouram.locale.intent.extra.HELP_URL", OnlineHelp.HELP_URL_PRE+"plugin/TimePicker");

		// Note: title set in onCreate
		helpIntent.putExtra(TimedProfiles.INTENT_TITLE, getTitle());

		menu.add(R.string.onlinehelp)
			.setIcon(android.R.drawable.ic_menu_help).setIntent(helpIntent);
		menu.add(0, MENU_DONT_SAVE, 0, android.R.string.cancel)
			.setIcon(android.R.drawable.ic_menu_close_clear_cancel).getItemId();
		menu.add(0, MENU_SAVE, 0, R.string.plugin_save)
			.setIcon(android.R.drawable.ic_menu_save).getItemId();
		return true;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean onMenuItemSelected(final int featureId, final MenuItem item)
	{
		switch (item.getItemId())
		{
			case MENU_SAVE:
			{
				finish();
				return true;
			}
			case MENU_DONT_SAVE:
			{
				isCancelled = true;
				finish();
				return true;
			}
		}

		return super.onOptionsItemSelected(item);
	}

}
